package cn.zgr.web;

import cn.zgr.dao.UserDAO;
import cn.zgr.entity.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginServlet extends HttpServlet {

		@Override
		protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

			request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();

			//读取用户名和密码
			String username = request.getParameter("username");
			String pwd = request.getParameter("pwd");

			System.out.println("用户名密码：" + username + pwd);
			/*
			 * 查询数据库，看是否有匹配的记录,
			 * 如果有，则登录成功，重定向到success.jsp。
			 * 如果没有，则登录失败，转发到login.jsp,
			 * 并提示"用户名或密码错误"。
			 */
			UserDAO dao = new UserDAO();
			System.out.println("dao: " + dao);
			try {
				User user = dao.findByUsername(username);
				if(user != null && user.getPwd().equals(pwd)) {
					System.out.println("确定用户： " + user);
					/*
					 * 登录成功,将一些数据绑订到
					 * session对象上，为session验证
					 * 做准备。
					 */
					HttpSession session = request.getSession();
					session.setAttribute("user", user);
					response.sendRedirect("success.jsp");
				}else {
					//登录失败
					request.setAttribute("login_failed", "用户名或密码错误");
					request.getRequestDispatcher("login.jsp").forward(request, response);
				}
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("异常！！！！！");
				out.println("系统繁忙，稍后重试");
			}


		}
}


